package com.powergisol.gis.util;

import com.powergisol.gis.vo.TabServiceVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class FileUpload {
    private static Logger logger = LoggerFactory.getLogger(FileUpload.class);
    /**
     * 文件上传
     * @param file
     * @param attachmentUrlSet
     * @param vo
     * @return
     */
    public static Result fileUpload(MultipartFile file, String attachmentUrlSet, TabServiceVo vo){
        String assinSuffixName = vo.getAssinSuffixName();
        Result result = new Result();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if(!(".zip").equalsIgnoreCase(suffixName)){
            return result.failure(-1, "请上传zip压缩文件");
        }
        String destUrl = attachmentUrlSet + File.separator + "temp"+ File.separator +assinSuffixName + File.separator +vo.getUuid()+File.separator+vo.getName() + suffixName;
        //1、存储到临时文件
        File dest = new File(destUrl);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            logger.error("文件上传失败",e.getStackTrace());
            return result.failure(-1, "上传失败,请重新上传");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileName", fileName);
        map.put("destUrl", destUrl);
        logger.info("文件已上传:{}",map);
        result.setData(map);
        return result;
    }
}
